package com.mew.lobby.handler.gameconf;

import com.mew.common.dc.redis.GameRoomRedisService;
import com.mew.common.dc.redis.LevelConfigRedisService;
import com.mew.common.dc.redis.UserProfileRedisService;
import com.mew.common.enm.DataStateType;
import com.mew.common.entity.config.Room;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.bo.MewSession;
import com.mew.lobby.annotation.LobbyHandler;
import com.mew.lobby.config.LobbySession;
import com.mew.lobby.config.LobbySessionManager;
import com.mew.lobby.message.request.LoadRoomRequestMessage;
import com.mew.lobby.message.response.RoomInfoMessage;
import com.mew.lobby.message.response.RoomListResponseMessage;
import com.mew.lobby.net.LobbyHandlerMapCmdType;
import com.mew.lobby.net.MewHandler;
import com.zebra.remoting.protocol.ZebraCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author King.Song
 * @Date 2020/11/14 0014
 **/
@Service
@Slf4j
@LobbyHandler(LobbyHandlerMapCmdType.RoomList)
public class LoadRoomListHandler implements MewHandler<LoadRoomRequestMessage> {


    @Autowired
    private GameRoomRedisService gameRoomRedisService;
//    @Autowired
//    private LevelConfigRedisService levelConfigRedisService;
//    @Autowired
//    private UserProfileRedisService userProfileRedisService;

    @Override
    public void handle(ZebraCommand<LoadRoomRequestMessage> zebraCommand, MewSession session) {
        if (zebraCommand.getRequest().getGameId() < 1){
            zebraCommand.sendFailureCode(ResponseCode.ParamInvalid.code());
            return;
        }

        List<Room> roomList = gameRoomRedisService.findRoomByGameId(zebraCommand.getRequest().getGameId());
        if (null == roomList || roomList.isEmpty()){
            zebraCommand.sendFailureCode( ResponseCode.GameRoomNotConfig.code());
            return;
        }

        LobbySession lobbySession = LobbySessionManager.getInstance().getSession(zebraCommand.getUserId());
        if (lobbySession.getWhiteList() == 0){
            roomList = roomList.stream().filter(r -> r.getState() == DataStateType.Active.code()).collect(Collectors.toList());
            if (roomList.isEmpty()){
                zebraCommand.sendFailureCode( ResponseCode.GameRoomNotConfig.code());
                return;
            }
        }

//        Profile profile = userProfileRedisService.getRedisProfileById(zebraCommand.getUserId());
        List<RoomInfoMessage> list = roomList.stream().map(room -> {
            //String bets = levelConfigRedisService.getBetStrs(profile.getUserLevel(), room.getRoomType());
            return new RoomInfoMessage().buildData(room, "");
        }).collect(Collectors.toList());

        RoomListResponseMessage message = RoomListResponseMessage.builder().list(list).build();
        zebraCommand.sendMessage(message);
    }



}
